<script setup>
import ExcelJS from 'exceljs';
import Loading from '@/components/loading/index.vue'
import { getMallList } from '@/utils/auth.js'
import { ref } from 'vue'
import { ElMessage } from 'element-plus';
import { updateExcel, erpExcel } from '@/api/stat.js'
const show = ref(false)
const mallIds = ref()
const props = defineProps({
	list: {
		type: Array,
	},
	title: {
		type: String
	},
	text: {
		type: String
	}
})
const emit = defineEmits(['upDateList']);
// import * as XLSX from 'xlsx';
const messageReactive = ref(null);
const inputRef = ref(null);
const hasDuplicate = ref(false);
const shopList = ref([])
const percentage = ref(0)
// 获取店铺接口方法
getMallList().then(res => {
	shopList.value = res
})
const onDownloadProgress_getTxtUid = (progressEvent) => {
	let percent = Math.round((progressEvent.loaded / progressEvent.total) * 100)
	percentage.value = percent
}
// 导入excel文件
const importExcel = (event) => {
	//获取选择的文件
	const files = event.target.files;
	if (files[0].type !== "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet") return ElMessage.error('文件格式不支持,仅支持xlsx格式文件');
	//创建Workbook实例
	const workbook = new ExcelJS.Workbook();
	// 使用FileReader对象来读取文件内容
	const fileReader = new FileReader();
	// 二进制字符串的形式加载文件
	fileReader.readAsArrayBuffer(files[0]);
	fileReader.onload = (ev) => {
		// 从 buffer中加载数据解析
		workbook.xlsx.load(ev.target.result).then(async (workbook) => {
			// console.log(111, workbook.getWorksheet(0))
			// 获取第一个worksheet内容
			const worksheet = workbook.getWorksheet();
			// 获取第一行的标题
			const headers = [];
			worksheet.getRow(1).eachCell((cell) => {
				headers.push(cell.text);
			});
			// 创建一个空的JavaScript对象数组，用于存储解析后的数据
			const data = [];
			// 遍历工作表的每一行（从第二行开始，因为第一行通常是标题行）
			for (let rowNumber = 2; rowNumber <= worksheet.rowCount; rowNumber++) {
				//richText: Array(2)0: {text: 'SKU'}1: {font: {…}, text: '成本价格'
				const rowData = {};
				const row = worksheet.getRow(rowNumber);
				// 遍历当前行的每个单元格
				row.eachCell((cell, colNumber) => {
					// 获取标题对应的键，并将当前单元格的值存储到相应的属性名中
					rowData[headers[colNumber - 1]] = cell.value;
				});
				// 将当前行的数据对象添加到数组中
				data.push(rowData);
			}
			const uniqueData = data.reduce((accumulator, item) => {
				const existingItem = accumulator.find(
					(existing) => existing.skuExtCode === item['SKU货号']
				);
				if (!existingItem && props.title == "SKU成本价格") {
					if (item['SKU货号'] && item['SKU成本价格']) {
						accumulator.push({
							skuExtCode: item['SKU货号'].toString(),
							costPrice: item[props.title].toString(),
						});
					}
				} else if (!existingItem && props.title == 'ERP货号') {
					if (item['SKU货号'] && item[props.title]) {
						accumulator.push({
							skuExtCode: item['SKU货号'].toString(),
							erpCode: item[props.title].toString(),
						});
					}
				} else {
					hasDuplicate.value = true;
				}
				return accumulator;
			}, []);
			inputRef.value.value = null;
			try {
				// messageReactive.value = ElMessage.loading('正在导入文件数据', {
				// 	duration: 0,
				// });
				messageReactive.value = ElMessage({
					icon: Loading,
					showClose: false,
					message: '正在导入文件数据...',
					duration: 0,
				})
				props.title == "ERP货号" ? await erpExcel({ mallId: mallIds.value, data: uniqueData }, onDownloadProgress_getTxtUid) : await updateExcel({ mallId: mallIds.value, data: uniqueData }, onDownloadProgress_getTxtUid);
				emit('upDateList');
				ElMessage.success(hasDuplicate.value ? '导入完成,该文件有重复数据' : '导入完成');
				onClose()
			} catch (e) {
				if (messageReactive.value) {
					messageReactive.value.close();
					messageReactive.value = null;
				}
				ElMessage.error('导入失败');
			} finally {
				if (messageReactive.value) {
					messageReactive.value.close();
					messageReactive.value = null;
				}
			}
		});
	};
};
const importData = async () => {
	show.value = true
}
// 保存
const onSubmit = () => {
	if (!mallIds.value) return ElMessage.error('请先选择店铺')
	inputRef.value.click();
}
// 取消
const onClose = () => {
	show.value = false;
	mallIds.value = null
};
// ElMessage({
// 	showClose: true,
// 	icon: 'Loading',
// 	message: '正在导入文件数据',
// })
</script>

<template>
	<input type="file" ref="inputRef" @change="importExcel" accept=".xlsx" v-show="false">
	<el-button @click="importData" style="margin-left:10px" color="#de1b09">{{ props.text }}</el-button>
	<Dialog :visible="show" title="请选择导入的店铺" @onClose="onClose" @onSubmit="onSubmit" width="40%" height="20%">
		<el-form label-align="left" label-width="auto" label-placement="left">
			<el-form-item label="商品管理">
				<el-select v-model="mallIds" placeholder="请选择商铺" clearable>
					<el-option v-for="item in shopList" :value="item.mallId" :label="item.mallName" :key="item.mallId">
						<div class="flex items-center">
							<img :src="item.mallLogo" class="w-auto h-20px mr-5px">
							<span>{{ item.mallName }}</span>
						</div>
					</el-option>
				</el-select>
			</el-form-item>
		</el-form>
	</Dialog>
</template>

<style scoped></style>
